#      1.   选择了哔哩哔哩的客户端。
#      2.下载客户端，启动体验，测试模块登陆模块。
#      3.对启动过程进行分析。
#          3.1首先启动后，会出现同意框
#          3.2 出现加载文件，需要联网，等待即可。
#          3.3元素定位
#                 工具集合：uiautomatorviewer和hierarchyviewer都可以。
#       4.梳理登录流程
#          4.1 启动app
#          4.2 点击登录
#          4.3跳转到登录界面
#          4.4我们选择用户名密码登录
#          4.5定位用户名输入框，清空，输入用户名
#          4.6 定位密码输入框，清空，输入用户名密码
#          4.7 点击登录
#          4.8 断言是否成功

from time import sleep
from appium import webdriver
from androguard.core.bytecodes.apk import APK
import os

apk_path = "/Users/lexus/Downloads/iBiliPlayer-bili.apk"


def get_devices() -> list:
    all_devices = []
    cmd = "adb devices"
    reslut = os.popen(cmd).readlines()[1:]
    for item in reslut:
        if item != "\n":
            all_devices.append(str(item).split("\t")[0])
    return all_devices


def getPlatForm(dev: str) -> str:
    cmd = 'adb -s {} shell getprop ro.build.version.release'.format(dev)
    reslut = os.popen(cmd).readlines()[0]
    return str(reslut).split("\n")[0]


def get_apkname(apk):
    a = APK(apk, False, "r")
    return a.get_package()


def get_apk_lautc(apk):
    a = APK(apk, False, "r")
    return a.get_main_activity()


def isinstallapk(packname: str, devname: str) -> bool:
    cmd = "adb -s {} shell pm list packages -3".format(devname)
    reslut = os.popen(cmd).readlines()
    all_apkname = []
    for i in reslut:
        apkname = str(i).split('\n')[0].split(":")[1]
        all_apkname.append(apkname)
    if packname in all_apkname:
        return True
    return False


def uninstallapk(packname: str, devname: str) -> bool:
    cmd = "adb -s {} shell pm list packages -3".format(devname)
    reslut = os.popen(cmd).readlines()
    all_apkname = []
    for i in reslut:
        apkname = str(i).split('\n')[0].split(":")[1]
        all_apkname.append(apkname)
    if packname in all_apkname:
        cmd = 'adb -s %s uninstall %s ' % (devname, packname)
        os.system(cmd)
        return True
    return False


def installapk(paknamepath: str, devname: str) -> bool:
    cmd = 'adb -s %s install %s' % (devname, paknamepath)
    os.system(cmd)
    return True


def testqqlogin():
    packname = get_apkname(apk_path)
    dev = get_devices()[0]
    is_first_install = False
    # 1.判断是否安装app
    is_install = isinstallapk(packname, dev)
    if is_install is False:
        # 2.如果没有安装，则安装
        installapk(apk_path, dev)
        is_first_install = True

    # 3.启动apk测试
    apkname = get_apkname(apk_path)
    launcheractivity = get_apk_lautc(apk_path)
    desired_caps = {
        'platformName': 'Android',
        'deviceName': dev,  # adb  deivces
        'platformVersion': getPlatForm(dev),  # 从设置中可以获取
        'appPackage': apkname,  # 包名
        'appActivity': launcheractivity,  # apk的launcherActivity
        # 'skipServerInstallation': True
    }

    driver = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
    sleep(10)
    # 启动同意用户协议
    driver.find_element_by_id("tv.danmaku.bili:id/agree").click()
    if is_first_install:
        # 首次安装需要加载文件
        sleep(50)
    sleep(10)
    driver.find_element_by_xpath("//*[@text='登录']").click()
    driver.find_element_by_id('tv.danmaku.bili:id/btn_change_account').click()

    username = driver.find_element_by_id('tv.danmaku.bili:id/username')
    username.clear()
    username.send_keys("name")
    password = driver.find_element_by_id('tv.danmaku.bili:id/passport_tag')
    password.clear()
    password.send_keys("123456")
    login = driver.find_element_by_id('tv.danmaku.bili:id/btn_login')
    login.click()
    driver.close()


if __name__ == "__main__":
    testqqlogin()
